package example;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class CollectionTest {
    /**
     * collection类公共方法
     */
    @Test
    public void testCollection() {
        Collection<String> col = new ArrayList<>();

        col.add("45");
        col.add("333");
        col.addAll(Arrays.asList("26", "27"));

        Collection<String> col2 = new ArrayList<>();
        col2.add("abc");
        col2.add("ddd");
        col2.add("45");
        col2.add("98");
        col2.add("99");
        col2.add("100");

        col2.removeAll(Arrays.asList("99", "98"));
        col2.remove("100");

        col.addAll(col2);

        System.out.println(col.size());
        System.out.println(col.isEmpty());
        System.out.println(col.contains("45"));
        System.out.println(col.containsAll(col2));

        Iterator<String> iterator = col.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            System.out.println(next);
        }
        //取交集，返回给调用者col
        col.retainAll(col2);
        Object[] objects = col.toArray();
        System.out.println(col);

    }


    @Test  //工具类 也能操作map
    public void testCollectionUtil() {
        List<String> list = new ArrayList<>();
        list.add("dd");
        list.add("kkkk");
        list.add("bbbb");
        list.add("ccc");
        list.add("zz");
        list.add("nnn");
        list.add("eeee");
        list.add("jjj");
        list.add("gggggg");
        list.add("gggggg");
        System.out.println(list);

        //反转
        Collections.reverse(list);
        System.out.println("reverse " + list);

        //随机排列
        Collections.shuffle(list);
        System.out.println("shuffle " + list);

        Collections.sort(list);
        System.out.println("默认排序： " + list);

        //将list的第0个和第1个交换
        Collections.swap(list, 0, 1);
        System.out.println(list);

        //取最大 最小是min
        String obj = Collections.max(list);
        System.out.println(obj);

        //频率 获取元素出现次数
        int count = Collections.frequency(list, "gggggg");
        System.out.println(count);

        //拷贝 新集合必须预先开空间
        List<String> dest = Arrays.asList(new String[list.size()]);
        Collections.copy(dest, list);
        System.out.println(dest);

        //将线程不安全转换为线程安全
        List<String> synchronizedList = Collections.synchronizedList(list);
    }

}




